package com.qa.controller;

import com.github.pagehelper.PageInfo;
import com.qa.common.Const;
import com.qa.common.ServerResponse;
import com.qa.pojo.Tag;
import com.qa.pojo.User;
import com.qa.service.ITagService;
import com.qa.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author
 * @Date 2020/3/2 10:35
 * @Desc
 **/
@Controller
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private ITagService tagService;



    @GetMapping("/cms/user/listPage")
    public String userListPage() {
        return "userList";
    }

    @GetMapping("/cms/user/list")
    @ResponseBody
    public ServerResponse userList(@RequestParam(value = "userEmail", defaultValue = "") String userEmail,
                                   @RequestParam(value = "page", defaultValue = "1") Integer pageNum,
                                   @RequestParam(value = "limit", defaultValue = "10") Integer pageSize) {
        PageInfo<User> pageInfo = userService.getByEmail(userEmail, pageNum, pageSize);
        return ServerResponse.createBySuccess("查询成功！", pageInfo.getList(), pageInfo.getTotal());
    }

    @GetMapping("/cms/userEditPage")
    public String userEditPage(@RequestParam("userId") Integer userId, Model model) {
        User byId = userService.getById(userId);
        model.addAttribute("user", byId);
        return "userEditPage";
    }


    @GetMapping("/user/loginPage")
    public String loginPage(){
        return "loginPage";
    }


    @PostMapping("/user/login")
    @ResponseBody
    public ServerResponse userLogin(User user, HttpServletRequest request) {
        return userService.login(user, request);
    }

    @PostMapping("/user/register")
    @ResponseBody
    public ServerResponse register(User user) {
        return userService.register(user);
    }


    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @PostMapping("/cms/user/update")
    @ResponseBody
    public ServerResponse updateUser(@RequestBody User user) {
        return userService.updateUser(user);
    }




    @GetMapping("/user/request/question")
    public String requestQuestion(HttpServletRequest request, Model model) {
        User user = (User) request.getSession().getAttribute(Const.CURRENT_USER);
        List<Tag> tags = tagService.getByEmail(user.getEmail());
        model.addAttribute("tags", tags);
        return "question";
    }



    @GetMapping("/user/profile")
    public String userProfile() {
        return "profile";
    }

    @GetMapping("/user/logout")
    public String userLogout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "loginPage";
    }


}
